import { Ref, ref, watch } from 'vue'

export const setItem = <T>(key: string, val: T): T => {
  localStorage.setItem(key, JSON.stringify(val))
  return getItem(key)
}

export const getItem = (key: string) => {
  let storage: Ref<any> = JSON.parse(localStorage.getItem(key) || 'null')
  storage = ref(storage)
  watch(storage.value, () => setItem(key, storage.value))
  return storage.value
}

export const removeItem = (key: string) => {
  localStorage.removeItem(key)
}

export default {
  setItem,
  getItem,
  removeItem
}
